#include "mprpcconfig.h"

// 负责解析加载配置文件
void MprpcConfig::LoadConfigFile(const char* config_file)
{
    FILE* pf = fopen(config_file, "r");
    if(pf == nullptr)
    {
        std::cout << config_file << " does not exist!" << std::endl;
        exit(EXIT_FAILURE);
    }

    // 1.注释  2.正确的配置项  3.去掉开头多余的空格
    while(!feof(pf))
    {
        char buf[256] = {0};
        fgets(buf, 256, pf);
        
        std::string readBuf(buf);
        Trim(readBuf);

        // 过滤空串和注释
        if(readBuf.empty() || readBuf[0] == '#') continue;

        // 解析配置项
        size_t index = readBuf.find('=');
        if(index == std::string::npos) continue; // 配置项不合法

        std::string key;
        key = readBuf.substr(0, index);
        Trim(key);
        
        std::string value;
        size_t endIndex = readBuf.find('\n');
        value = readBuf.substr(index + 1, endIndex - index - 1);
        Trim(value);

        _configMap.insert({key, value});
    }
}

// 查询配置项信息
std::string MprpcConfig::Load(const std::string& key)
{
    auto it = _configMap.find(key);
    if(it == _configMap.end())
    {
        return "";
    }
    return it->second;
}

void MprpcConfig::Trim(std::string& srcBuf)
{
    // 去掉字符串前面多余的空格
    size_t index = srcBuf.find_first_not_of(' ');
    if(index != std::string::npos)
    {
        // 说明字符串前面有空格
        srcBuf = srcBuf.substr(index, srcBuf.size() - index);
    }

    // 去掉字符串后面多余的空格
    index = srcBuf.find_last_not_of(' ');
    if(index != std::string::npos)
    {
        // 说明字符串后面有空格
        srcBuf = srcBuf.substr(0, index + 1);
    }
}